package com.jie.langlangmall.controller;

import cn.hutool.core.collection.CollUtil;
import com.jie.langlangmall.common.api.CommonPage;
import com.jie.langlangmall.common.api.CommonResult;
import com.jie.langlangmall.common.constant.MessageConstant;
import com.jie.langlangmall.common.constant.StatusConstant;
import com.jie.langlangmall.dto.UmsAdminLoginParam;
import com.jie.langlangmall.dto.UmsAdminParam;
import com.jie.langlangmall.dto.UpdateAdminPasswordParam;
import com.jie.langlangmall.model.UmsAdmin;
import com.jie.langlangmall.model.UmsRole;
import com.jie.langlangmall.service.UmsAdminService;
import com.jie.langlangmall.service.UmsRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Jie
 * @Date 2024/11/22 10:31
 * @Email 3217998214@qq.com
 * @Description 后台用户管理
 */
@Slf4j
@RestController
@Tag(name = "UmsAdminController", description = "后台用户管理")
@RequestMapping("/admin")
public class UmsAdminController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private UmsRoleService roleService;

    @Operation(summary = "登录后返回token")
    @PostMapping("/login")
    public CommonResult<Map<String, String>> login(@Validated @RequestBody UmsAdminLoginParam umsAdminLoginParam) {
        // 超级用户 admin $2a$10$1QA5xTjB417Wb73NvDdT6./KHL6va/EZBn3swPD0EKJX19KisnOSu
        String token = adminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());
        if (StringUtils.isEmpty(token)) {
            // 用户名或者密码错误
            return CommonResult.validateFailed(MessageConstant.USERNAME_OR_PASSWORD_ERROR);
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @Operation(summary = "刷新token")
    @GetMapping("/refreshToken")
    private CommonResult<Map<String, String>> refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = adminService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed(MessageConstant.TOKEN_EXPIRED);
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    // TODO: 注册的时候添加头像上传功能
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public CommonResult<UmsAdmin> register(@Validated @RequestBody UmsAdminParam umsAdminParam) {
        UmsAdmin umsAdmin = adminService.register(umsAdminParam);
        if (umsAdmin == null) {
            return CommonResult.failed();
        } else {
            return CommonResult.success(umsAdmin);
        }
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/info")
    public CommonResult<Map<String, Object>> getAdminInfo(Principal principal) {
        if (principal == null) {
            return CommonResult.unauthorized(null);
        }
        // 获取用户名
        String username = principal.getName();
        UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
        log.info("登录的用户名：{}", username);
        Map<String, Object> data = new HashMap<>();
        // 用户名
        data.put("username", umsAdmin.getUsername());
        // 菜单
        data.put("menus", roleService.getMenuList(umsAdmin.getId()));
        // 头像
        data.put("icon", umsAdmin.getIcon());
        // 设置用户的角色
        List<UmsRole> roleList = adminService.getRoleList(umsAdmin.getId());
        if (CollUtil.isNotEmpty(roleList)) {
            List<String> roles = roleList.stream().map(UmsRole::getName).collect(Collectors.toList());
            data.put("roles", roles);
        }
        return CommonResult.success(data);
    }

    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public CommonResult<Object> logout(Principal principal) {
        adminService.logout(principal.getName());
        return CommonResult.success(null);
    }

    @Operation(summary = "根据用户名或姓名分页获取用户列表")
    @GetMapping("/list")
    public CommonResult<CommonPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        // TODO: 密码能不能返回？
        List<UmsAdmin> adminList = adminService.list(keyword, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(adminList));
    }

    @Operation(summary = "删除指定用户")
    @PostMapping("/delete/{id}")
    public CommonResult<Integer> delete(@PathVariable("id") Long id) {
        int count = adminService.delete(id);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @Operation(summary = "修改账号状态")
    @PostMapping("/updateStatus/{id}")
    public CommonResult<Object> updateStatus(@PathVariable("id") Long id, @RequestParam(value = "status") Integer status) {
        // TODO: 如果是超级管理员，需要修改状态吗？
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setStatus(status);
        int count = adminService.update(id, umsAdmin);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @Operation(summary = "修改指定用户信息")
    @PostMapping("/update/{id}")
    public CommonResult<Integer> update(@PathVariable("id") Long id, @RequestBody UmsAdmin admin) {
        int count = adminService.update(id, admin);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @Operation(summary = "获取指定用户信息")
    @GetMapping("/{id}")
    public CommonResult<UmsAdmin> getItem(@PathVariable("id") Long id) {
        UmsAdmin admin = adminService.getItem(id);
        return CommonResult.success(admin);
    }

    @Operation(summary = "修改指定用户密码")
    @PostMapping("/updatePassword")
    public CommonResult<Integer> updatePassword(@Validated @RequestBody UpdateAdminPasswordParam param) {
        int status = adminService.updatePassword(param);
        if (status == StatusConstant.SUCCESS) {
            return CommonResult.success(status);
        } else if (status == StatusConstant.SUBMIT_PARAM_ERROR) {
            return CommonResult.failed(MessageConstant.SUBMIT_PARAM_ERROR);
        } else if (status == StatusConstant.CANT_FIND_USER) {
            return CommonResult.failed(MessageConstant.CANT_FIND_USER);
        } else if (status == StatusConstant.OLD_PASSWORD_ERROR) {
            return CommonResult.failed(MessageConstant.OLD_PASSWORD_ERROR);
        } else {
            return CommonResult.failed();
        }
    }

    @Operation(summary = "给用户分配角色")
    @PostMapping("/role/update")
    public CommonResult<Integer> updateRole(@RequestParam("adminId") Long adminId,
                                            @RequestParam("roleIds") List<Long> roleIds) {
        int count = adminService.updateRole(adminId, roleIds);
        if (count == StatusConstant.SUCCESS) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @Operation(summary = "获取指定用户的角色")
    @GetMapping("/role/{adminId}")
    public CommonResult<List<UmsRole>> getRoleList(@PathVariable("adminId") Long adminId) {
        List<UmsRole> roleList = adminService.getRoleList(adminId);
        return CommonResult.success(roleList);
    }

}
